package com.huxiu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.model.HuaTiItem;
import com.huxiu.net.model.HuatiInfo;
import com.huxiu.net.responses.HuatiInfoResponse;
import com.huxiu.utils.Constants;
import com.huxiu.utils.ErrorResponseException;
import com.huxiu.utils.ImageLoaderOptions;
import com.huxiu.utils.JavaScriptinerface;
import com.huxiu.utils.Loading;
import com.huxiu.utils.NetUtil;
import com.huxiu.utils.Settings;
import com.huxiu.utils.UmenEvent;
import com.huxiu.utils.Utils;
import com.huxiu.view.ArticleWebView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import java.util.LinkedHashMap;
import java.util.Map;

public class HuaTiDetailActivity extends BaseActivity implements ArticleWebView.ArticleWebViewListener {
    //Tag
    private static final String TAG = HuaTiDetailActivity.class.getName();
    @ViewInject(R.id.webview)
    private ArticleWebView webview;

    @ViewInject(R.id.bottom_bar)
    private LinearLayout bottom_bar;
    @ViewInject(R.id.layout_back)
    private RelativeLayout layout_back;

    @ViewInject(R.id.text_comment)
    private TextView text_comment;

    @ViewInject(R.id.layout_share)
    private RelativeLayout layout_share;

    @ViewInject(R.id.img_group)
    private ImageView img_group;

    @ViewInject(R.id.text_group_name)
    private TextView text_group_name;

    @ViewInject(R.id.text_group_status)
    private TextView text_group_status;

    @ViewInject(R.id.layout_group_info)
    private RelativeLayout layout_group_info;

    @ViewInject(R.id.bottom_bar_right)
    private LinearLayout bottom_bar_right;
    @ViewInject(R.id.loading_view)
    private View loading_view;

    private String h5_url;

    private TextView titleView;

    private Thread mThread;

    private HuaTiItem mHuaTiItem;

    private HuaTiDetailActivity instance;

    private Handler mHandler = new Handler();

    private String id;
    private int isJoin = -1;
    public static JavaScriptinerface mJavaScriptinerface;


    private  Handler handler;
    private  Runnable runnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_huatidetail);
        instance = this;
        ViewUtils.inject(this);
        Loading.showLoading(instance);
        init();
        initdata();
    }

    private void init() {
        handler=new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                Utils.showToast(R.string.generic_failure);
                reLoadView.setVisibility(View.VISIBLE);
                Loading.closeLoading();
            }
        };
        handler.postDelayed(runnable, Constants.TIME_RELOADE);

        //注册广播接收者，并添加多个过滤器
        IntentFilter intent = new IntentFilter();
        intent.addAction(Constants.INTENT_HUATICOMMENT_SUCCESS);
        intent.addAction(Constants.INTENT_QUNZU_JOIN_CHANGE);
        LocalBroadcastManager.getInstance(APP.getInstance()).registerReceiver(mReceiver, intent);
        if (mHuaTiItem == null) {
            if (getIntent().hasExtra(Constants.GROUP_HUATI_ITEM_ID)) {
                id = getIntent().getStringExtra(Constants.GROUP_HUATI_ITEM_ID);
            } else if(getIntent().hasExtra(Constants.PUSH_ID_KEY)){
                id = getIntent().getStringExtra(Constants.PUSH_ID_KEY);
            }else{

            }
        }
    }

    private void initdata() {
        loaddata(0);
        if (!NetUtil.checkNet(instance)) {
            reLoadView.setVisibility(View.VISIBLE);
            Loading.closeLoading();
        }
    }

    private void initweb() {
        text_group_name.setText(mdata.forum.name);
        if (mdata.forum.is_join == 1) {
            text_group_status.setText(R.string.qunzu_huti_add);
            text_group_status.setTextColor(0xffbbbbbb);
        } else {
            text_group_status.setText(R.string.qunzu_huti_noadd);
        }
        ImageLoader.getInstance().displayImage(
                mdata.forum.pic_path + Constants.IMAGE_WEBP, img_group, ImageLoaderOptions.options);
        mJavaScriptinerface = new JavaScriptinerface(instance, mdata, webview);
        updateWebViewSettings(webview);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.addJavascriptInterface(mJavaScriptinerface, "android");
        webview.setWebViewClient(new webviewClient());
        webview.loadUrl(mdata.thread.h5_url);
        //                webview.loadUrl("file:///android_asset/index.html");
    }


    class webviewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

        }


        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Loading.closeLoading();
            loading_view.setVisibility(View.GONE);
            mJavaScriptinerface.thread_zan_ui();
            bottom_bar_right.setVisibility(View.VISIBLE);
            handler.removeCallbacks(runnable);
        }
    }


    private Intent intent;

    @OnClick({R.id.layout_back, R.id.layout_share, R.id.layout_group_info, R.id.text_comment, R.id.reLoadView})
    public void mOnClick(View v) {
        switch (v.getId()) {
            case R.id.text_comment:
                if (!Settings.isLoggedIn()) {
                    Utils.askLogIn(instance);
                    return;
                }
                if (!(isJoin == 1)) {
                    Utils.showToast("您还未加入该小组");
                    return;
                }
                intent = new Intent(this, SubmitHuatiCommentActivity.class);
                intent.putExtra(Constants.HUATI_ID_KEY, mdata.thread.id);
                intent.putExtra("type",Constants.COMMENT_ADD);
                intent.putExtra(UmenEvent.COMMENT_INTENT_KEY,UmenEvent.TOPIC_DETAIL_REPLY_TOPIC);
                intent.putExtra("type", Constants.COMMENT_ADD);
                this.startActivity(intent);
                this.overridePendingTransition(R.anim.activity_open, 0);
                break;
            case R.id.layout_back:
                if (webview.canGoBack()) {
                    webview.goBack();
                } else {
                    HuaTiDetailActivity.this.finish();
                }
                break;
            case R.id.layout_share:
                new AsyncTask<Void, Void, Void>() {
                    Bitmap bmp = null;

                    @Override
                    protected Void doInBackground(Void... params) {
                        bmp = ImageLoader.getInstance().loadImageSync(mdata.forum.pic_path + Constants.IMAGE_WEBP);
                        //                        bmp = ImageLoader.getInstance().loadImageSync("https://gd2.alicdn.com/bao/uploaded/i2/TB1uH32KpXXXXcqXFXXXXXXXXXX_!!0-item_pic.jpg");
                        return null;
                    }
                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        Utils.launchShareActivity(instance,
                                mdata.thread.title+"", mdata.thread.share_url+"", "doc", mdata.forum.pic_path+"",
                                Utils.SubString(mdata.thread.content), bmp, UmenEvent.HUATI_SHARE);
                    }
                }.execute();
                Log.e("aaaa", "aaaaa" + mdata.thread.toString());
                Log.e("aaaa", "title" + mdata.thread.title.toString() + "h5_url" + mdata.thread.h5_url + "pic_path" + mdata.forum.pic_path + "");
                break;
            case R.id.layout_group_info:
                UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_DETAIL, UmenEvent.TOPIC_DETAIL_CLICK_TOP);
                intent = new Intent(instance, QunZuDetailActivity.class);
                intent.putExtra(Constants.GROUP_HUTTI_ITEM_KEY, mdata.forum.toString());
                //                startActivity(intent);
                startActivityForResult(intent, 100);
                break;
            case R.id.reLoadView:
                reLoadView.setVisibility(View.GONE);
                Loading.showLoading(instance);
                initdata();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {//联系人activity返回的data
                int is_join_num = data.getIntExtra("is_join_num", 4);
                isJoin = is_join_num;
                if (is_join_num == 1) {
                    text_group_status.setText(R.string.qunzu_huti_add);
                } else {
                    text_group_status.setText(R.string.qunzu_huti_noadd);
                }
            }
        }
    }

    @Override
    public void onScrollOverOneScreen() {
    }

    @Override
    public void onScrollLessThanOneScreen() {

    }

    private HuatiInfo mdata;

    //点赞功能
    private void loaddata(int page) {
        String url = NetworkConstants.THREAD;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("id", id);
        params.put("page", page + "");
        GsonRequest<HuatiInfoResponse> request = new GsonRequest<>(url, Request.Method.POST,
                HuatiInfoResponse.class, false, params, new Response.Listener<HuatiInfoResponse>() {
            @Override
            public void onResponse(HuatiInfoResponse response) {
                if (response.isSuccess()) {
                    mdata = response.data;
                    isJoin = mdata.forum.is_join;
                    initweb();
                } else {
                    Utils.showToast(response.error.message);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                reLoadView.setVisibility(View.VISIBLE);
                Loading.closeLoading();
                Throwable t = error.getCause();

                if (t instanceof ErrorResponseException) {
                } else {
                    Utils.showToast(R.string.generic_failure);
                }
            }
        });
        BaseActivity.getmQueue().add(request);
    }


    //广播接收者
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constants.INTENT_HUATICOMMENT_SUCCESS)) {
                webview.reload();
            } else if (action.equals(Constants.INTENT_QUNZU_JOIN_CHANGE)) {
                int is_join_num = intent.getIntExtra("is_join_status", 4);
                isJoin = is_join_num;
                if (is_join_num == 1) {
                    text_group_status.setText(R.string.qunzu_huti_add);
                } else {
                    text_group_status.setText(R.string.qunzu_huti_noadd);
                }
            }
        }
    };


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }
}
